<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          规则名称：
          <NInput style="width: 200rem" placeholder="请输入规则名称" v-model:value="paginationReactive.ruleName" clearable />
          <NButton type="primary" style="width: 78rem" ghost @click="() => {
            ; (paginationReactive.page = 1), getCheckRulesList()
          }
            ">
            查询
          </NButton>
        </NSpace>
        <NSpace>
          <NButton type="primary" style="width: 115rem" @click="$router.push({ name: 'OA/Office/RulesAdd' })">
            新增考勤规则
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VDialogContent @close="modalVisible = false" @submit="submit" :title="title">
      <div style="
          width: 300rem;
          height: 100rem;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
        ">
        {{ content }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { h, reactive, onDeactivated, ref, watch } from 'vue'
import { NSpace, NInput, NButton, NDataTable, NPagination, useMessage, NModal } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { CheckModel } from '@/api/checkRules'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useViewerStore } from '@/views/OA/Common/store'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const columns: DataTableColumns = [
  {
    title: '规则名称',
    key: 'ruleName',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '工作时间',
    key: 'workTime',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '周一',
    key: 'mon',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '周二',
    key: 'tue',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '周三',
    key: 'wed',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '周四',
    key: 'thu',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '周五',
    key: 'fri',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '周六',
    key: 'sat',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '周日',
    key: 'sun',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '应用员工',
    key: 'applicationEmployees',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 120,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({ path: '/OA/Office/RulesUpdate', query: { id: row.id } })
          }
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          color: useStore.color['delete'],
          onClick: () => {
            title.value = '删除提示'
            content.value = '您确定删除该条考勤规则吗？'
            rulesId.value = row.id
            modalVisible.value = true
          }
        },
        {
          default: () => '删除'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: async () => {
            title.value = '生成考勤排班提示'
            rulesId.value = row.id
            const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
              module: 'checkRules',
              api: 'checkWorkAttendanceRule',
              uri: {
                id: row.id as never
              }
            })
            if (error) return
            if (res.code !== 0) return
            content.value = res.data
              ? '当前规则范围包含今日以前的日期，确定生成吗？'
              : '您确定生成该条考勤排班数据吗？'
            modalVisible.value = true
          }
        },
        {
          default: () => '生成排班数据'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 50,
  ruleName: null, //规则名称
  onChange: (page: number) => {
    paginationReactive.page = page
    getCheckRulesList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getCheckRulesList()
  }
})
// 提交
const rulesId = ref()
const title = ref()
const content = ref()
const modalVisible = ref(false)
const submit = () => {
  title.value == '删除提示' ? rulesDelete() : rulesCreate()
}
// 删除
const rulesDelete = async () => {
  tableLoading.value = true
  modalVisible.value = false
  const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
    module: 'checkRules',
    api: 'rulesDelete',
    override: {
      data: [rulesId.value]
    }
  })
  if (error) return message.error('删除失败')
  if (res.code !== 0) return message.error('删除失败')
  message.success('删除成功')
  getCheckRulesList()
}
// 生成排班数据
const rulesCreate = async () => {
  tableLoading.value = true
  modalVisible.value = false
  const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
    module: 'checkRules',
    api: 'workSave',
    override: {
      params: {
        id: rulesId.value
      }
    }
  })
  if (error) return message.error('生成排班失败')
  if (res.code !== 0) return message.error('生成排班失败')
  message.success('生成排班成功')
  getCheckRulesList()
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getCheckRulesList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<CheckModel>>({
    module: 'checkRules',
    api: 'rulesList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        ruleName: paginationReactive.ruleName
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  paginationReactive.itemCount = res.data.totalCount
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getCheckRulesList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Office/checkRules') {
      getCheckRulesList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
